package com.ch.ms.server.base.tools;

import com.ch.ms.server.base.client.MapleClientSession;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.net.InetSocketAddress;

public class ChannelUtils {


    private static AttributeKey<MapleClientSession> CLIENT_SESSION_ATTRIBUTE_KEY = AttributeKey.valueOf("client_session");

    /**
     * 添加新的会话
     *
     * @param channel
     * @return
     */
    public static void createMapleClientSession(Channel channel) {
        MapleClientSession mapleClientSession = new MapleClientSession(channel);
        Attribute<MapleClientSession> sessionAttr = channel.attr(CLIENT_SESSION_ATTRIBUTE_KEY);
        sessionAttr.set(mapleClientSession);
    }


    public static void removeMapleClientSession(MapleClientSession session) {

        session.getChannel().attr(CLIENT_SESSION_ATTRIBUTE_KEY).set(null);
    }

    public static MapleClientSession getMapleClientSession(Channel channel) {
        Attribute<MapleClientSession> sessionAttr = channel.attr(CLIENT_SESSION_ATTRIBUTE_KEY);
        return sessionAttr.get();
    }

    public static String getIp(Channel channel) {
        return ((InetSocketAddress) channel.remoteAddress()).getAddress().toString().substring(1);
    }

}
